package com.hhf.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhf.springboot.common.DataGroupByDateDTO;
import com.hhf.springboot.common.ErrorCode;
import com.hhf.springboot.constant.CommonConstant;
import com.hhf.springboot.exception.ThrowUtils;
import com.hhf.springboot.mapper.UserSignMapper;
import com.hhf.springboot.model.dto.userSign.UserSignQueryRequest;
import com.hhf.springboot.model.entity.UserSign;
import com.hhf.springboot.model.entity.User;
import com.hhf.springboot.model.vo.UserSignVO;
import com.hhf.springboot.model.vo.UserVO;
import com.hhf.springboot.service.UserSignService;
import com.hhf.springboot.service.UserService;
import com.hhf.springboot.utils.SqlUtils;
import com.hhf.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户签到服务实现
 *
 * @author hhf
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@Service
@Slf4j
public class UserSignServiceImpl extends ServiceImpl<UserSignMapper, UserSign> implements UserSignService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param userSign
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validUserSign(UserSign userSign, boolean add) {
        ThrowUtils.throwIf(userSign == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Date signTime = userSign.getSignTime();
        Long userId = userSign.getUserId();

        // 创建数据时，参数不能为空
        if (add) {
            // TODO 补充校验规则
            ThrowUtils.throwIf(userId == null, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(signTime == null, ErrorCode.PARAMS_ERROR);
        }
    }

    /**
     * 获取查询条件
     *
     * @param userSignQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<UserSign> getQueryWrapper(UserSignQueryRequest userSignQueryRequest) {
        QueryWrapper<UserSign> queryWrapper = new QueryWrapper<>();
        if (userSignQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = userSignQueryRequest.getId();
        Date signTime = userSignQueryRequest.getSignTime();
        String sortField = userSignQueryRequest.getSortField();
        String sortOrder = userSignQueryRequest.getSortOrder();
        Long userId = userSignQueryRequest.getUserId();

        // 精确查询
        // 处理 signTime 以进行模糊查询
        if (signTime != null) {
            LocalDate signDate = signTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            // 使用 LocalDateTime 创建起始和结束时间
            LocalDateTime startDateTime = signDate.atStartOfDay();
            LocalDateTime endDateTime = signDate.plusDays(1).atStartOfDay();

            // 转换为 Instant 对象
            Instant startDate = startDateTime.atZone(ZoneId.systemDefault()).toInstant();
            Instant endDate = endDateTime.atZone(ZoneId.systemDefault()).toInstant();

            // 使用 between 来查询 sign_in_time 的起止时间
            queryWrapper.between("sign_time", startDate, endDate);
        }

        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取用户签到封装
     *
     * @param userSign
     * @param request
     * @return
     */
    @Override
    public UserSignVO getUserSignVO(UserSign userSign, HttpServletRequest request) {
        // 对象转封装类
        UserSignVO userSignVO = UserSignVO.objToVo(userSign);

        // TODO 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = userSign.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        userSignVO.setUser(userVO);

        return userSignVO;
    }

    /**
     * 分页获取用户签到封装
     *
     * @param userSignPage
     * @param request
     * @return
     */
    @Override
    public Page<UserSignVO> getUserSignVOPage(Page<UserSign> userSignPage, HttpServletRequest request) {
        List<UserSign> userSignList = userSignPage.getRecords();
        Page<UserSignVO> userSignVOPage = new Page<>(userSignPage.getCurrent(), userSignPage.getSize(), userSignPage.getTotal());
        if (CollUtil.isEmpty(userSignList)) {
            return userSignVOPage;
        }
        // 对象列表 => 封装对象列表
        List<UserSignVO> userSignVOList = userSignList.stream().map(userSign -> {
            return UserSignVO.objToVo(userSign);
        }).collect(Collectors.toList());

        // TODO 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = userSignList.stream().map(UserSign::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 填充信息
        userSignVOList.forEach(userSignVO -> {
            Long userId = userSignVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            userSignVO.setUser(userService.getUserVO(user));
        });
        // endregion

        userSignVOPage.setRecords(userSignVOList);
        return userSignVOPage;
    }

    /**
     * 分按日期分组查询用户签到新增数量
     *
     * @param beginDate 开始时间
     * @param endDate   结束时间
     * @return
     */
    @Override
    public List<DataGroupByDateDTO> countByDay(Date beginDate, Date endDate) {
        QueryWrapper<UserSign> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DATE_FORMAT(create_time, '%Y-%m-%d') AS day", "COUNT(1) AS num");
        queryWrapper.ge("create_time", beginDate);
        queryWrapper.le("create_time", endDate);
        queryWrapper.groupBy("day");
        queryWrapper.orderByAsc("day");
        // 执行查询
        List<Map<String, Object>> results = this.baseMapper.selectMaps(queryWrapper);
        // 映射到 DataGroupByDateDTO
        return results.stream().map(result -> {
            DataGroupByDateDTO dto = new DataGroupByDateDTO();
            dto.setDay(DateUtils.parse(result.get("day").toString(), DateUtils.FMT_YMD));
            dto.setNum((Long) result.get("num"));
            return dto;
        }).collect(Collectors.toList());
    }


}
